import asyncio, time
from PySide6.QtCore import QObject, Signal
from bleak.backends.device import BLEDevice
from bleak.backends.scanner import AdvertisementData
from Communicate.BleFunction.BleDeviceInfo import BleDeviceInfo
from bleak import BleakScanner
from threading import Thread

class BleDiscover(QObject):
    DiscoverStartd = Signal()
    DiscoverStopped = Signal()
    DeviceDiscovered = Signal(BleDeviceInfo)

    def __init__(self):
        super().__init__()

        self.__thread:Thread = None
        self.__scanner = BleakScanner(self.__DiscoverCB)
        self.__started = False
    
    def __DiscoverThread(self):
        asyncio.run(self.__DiscoverProcess())
        while self.__started:
            time.sleep(0.1)

    async def __DiscoverProcess(self):
        await self.__scanner.start()
        self.DiscoverStartd.emit()
        
        while self.__started:
            await asyncio.sleep(0.1)
            
        await self.__scanner.stop()
        self.DiscoverStopped.emit()
    
    def __DiscoverCB(self, device: BLEDevice, advertisement_data: AdvertisementData):
        if (device.name is not None):
            self.DeviceDiscovered.emit(BleDeviceInfo(device, advertisement_data))

    def StartDiscover(self):
        if not self.__started:
            self.__started = True
            self.__thread:Thread = Thread(target = self.__DiscoverThread)
            self.__thread.start()

    def StopDiscover(self):
        if self.__started and self.__thread is not None:
            self.__started = False
            self.__thread.join()
